package com.swp.oa.sys.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.swp.oa.sys.dto.domian.DepartmentDto;
import com.swp.oa.sys.dto.domian.LogDto;
import com.swp.oa.sys.dto.domian.UserDto;
import com.swp.oa.sys.dto.page.EasyuiDataGridJson;
import com.swp.oa.sys.dto.page.JsonMessage;
import com.swp.oa.sys.service.IAuditService;
import com.swp.oa.sys.service.IDepartmentService;
import com.swp.oa.sys.service.IUserService;
import com.swp.oa.sys.util.Pager;

@Controller
@RequestMapping(value = "/user/")
public class UserController extends BaseController{

	@Autowired
	private IUserService userService;
	@Autowired
	private IDepartmentService departmentService;
	@Autowired
	private IAuditService auditService;
	// 返回用户管理主页
	@RequestMapping("/Index")
	public String userIndex() {
		return "/User/Index";
	}
	
	//获取用户列表
	@RequestMapping(value = "/GetUserList", method = RequestMethod.POST)
	@ResponseBody
	public EasyuiDataGridJson getUserList(int page, int rows, WebRequest request) {
		EasyuiDataGridJson json = new EasyuiDataGridJson();
		String userName = request.getParameter("name");
		String createdateStart = request.getParameter("createdatetimeStart");
		String createdateEnd = request.getParameter("createdatetimeEnd");
		String updatedateStart = request.getParameter("modifydatetimeStart");
		String updatedateEnd = request.getParameter("modifydatetimeEnd");
		String orgIds = request.getParameter("orgIds");
		String[] orgArray = null;
		if (StringUtils.isNotBlank(orgIds)) {
			orgArray = orgIds.split(",");
		}
//		System.out.println("userName: " + userName);
//		System.out.println("orgIds: " + orgIds);
//		System.out.println("updatedateStart: " + updatedateStart);
//		System.out.println("updatedateEnd: " + updatedateEnd);
		Pager pager = userService.getUserList(page, rows, userName,createdateStart,
				createdateEnd, updatedateStart, updatedateEnd,orgArray);
		if(pager != null){
			json.setTotal(pager.getTotalCount());
			json.setRows(pager.getRows());
			return json;			
		}
		return null;
	}

	// 返回创建用户界面
	@RequestMapping(value = "/toCreateUser")
	public String toCreateUser(Model model, String departmentId) {
//		System.out.println("toCreateUser departmentId: " + departmentId);
		if(departmentId != null && !departmentId.equals("")){
			model.addAttribute("departmentId", departmentId);			
		}else{
			DepartmentDto deptDto = departmentService.getRootDepartmentModel();
			if(deptDto != null){
				departmentId = deptDto.getId();
				model.addAttribute("departmentId", departmentId);				
			}
		}
//		DepartmentModel deptModel = departmentService.getByDeptIdToModel(departmentId);
//		model.addAttribute("departmentName", deptModel.getName());
		return "/User/Create";
	}

	// 创建用户
	@RequestMapping(value = "/createUser")
	@ResponseBody
	public JsonMessage createUser(HttpServletRequest request) {
		UserDto user = new UserDto();
		JsonMessage jsonMsg = new JsonMessage();
		if (userService.existUserName(request.getParameter("userName"))) {
			jsonMsg.setSuccess(false);
			jsonMsg.setMsg("用户名已存在！");
			jsonMsg.setObj("用户名已存在！");
		} else {
			user.setUserName(request.getParameter("userName"));
			user.setRealName(request.getParameter("realName"));
			user.setGender(request.getParameter("gender"));
			user.setDepartmentId(request.getParameter("departmentId"));
			if (StringUtils.isNotBlank(request.getParameter("status"))) {
				user.setStatus(request.getParameter("status"));
			}
			user.setPassword(request.getParameter("password"));
			user.setMobile(request.getParameter("mobile"));
			user.setEmail(request.getParameter("email"));
			String currentUserName = getCurrentUserName(request);
			user.setCreateUser(currentUserName);
			System.out.println("getCurrentUserName: " + currentUserName);
			try {
				userService.save(user);
				UserDto userModel = userService.getUserByUserName(currentUserName);
				// 保存日志记录
				LogDto logModel = new LogDto();
				logModel.setUserId(userModel.getId());
				logModel.setUserName(currentUserName);
				logModel.setContent(currentUserName + "添加了用户：" + user.getUserName());
				auditService.saveLog(logModel);
			} catch (Exception e) {
				e.printStackTrace();
				jsonMsg.setSuccess(false);
				jsonMsg.setMsg("添加用户出错！");
				jsonMsg.setObj(e.getMessage());
				return jsonMsg;
			}
			jsonMsg.setSuccess(true);
			jsonMsg.setMsg("添加用户成功！");
		}
		return jsonMsg;
	}

	// 返回编辑用户界面
	@RequestMapping(value = "/toEditUser")
	public String toEditUser(Model model, String userId) {
		
		model.addAttribute("userId", userId);
		return "/User/Edit";
	}

	// 返回编辑用户数据
	@RequestMapping(value = "/editUserForm")
	@ResponseBody
	public UserDto editUserForm(String userId) {
		UserDto user = userService.getUserByUserId(userId);
		user.setPassword("");
		String departmentId = departmentService.getDeptIdByUserId(userId);
		user.setDepartmentId(departmentId);
		return user;
	}

	// 编辑用户
	@RequestMapping(value = "/editUser")
	@ResponseBody
	public JsonMessage editUser(HttpServletRequest request, UserDto user) {
		JsonMessage jsonMsg = new JsonMessage();
		if (StringUtils.isNotBlank(user.getPassword())) {
			user.setPassword(user.getPassword());
		}
		String currentUserName = getCurrentUserName(request);
		user.setUpdateUser(currentUserName);
//		user.setUpdateDate(DateUtil.getNowTime());
		try {
			System.out.println("update user： "+ user.toString());
			userService.update(user);
			UserDto userModel = userService.getUserByUserName(currentUserName);
			
			// 保存日志记录
			LogDto logModel = new LogDto();
			logModel.setUserId(userModel.getId());
			logModel.setUserName(currentUserName);
			logModel.setContent(currentUserName + "修改了用户：" + user.getUserName());
			auditService.saveLog(logModel);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMsg.setSuccess(false);
			jsonMsg.setMsg("编辑用户失败！");
			jsonMsg.setObj(e.getMessage());
			return jsonMsg;
		}
		jsonMsg.setSuccess(true);
		jsonMsg.setMsg("编辑用户成功！");
		return jsonMsg;
	}

	// 批量删除用户
	@RequestMapping(value = "/deleteUser")
	@ResponseBody
	public JsonMessage deleteUser(HttpServletRequest request, String userIds) {
		String[] userIdArray = userIds.split(",");
		JsonMessage jsonMsg = new JsonMessage();
		try {
			String result = userService.deleteUser(userIdArray);
			String currentUserName = getCurrentUserName(request);
			UserDto userModel = userService.getUserByUserName(currentUserName);
			// 保存日志记录
			LogDto logModel = new LogDto();
			logModel.setUserId(userModel.getId());
			logModel.setUserName(currentUserName);
			logModel.setContent(currentUserName + "修改了用户：" + result);
			auditService.saveLog(logModel);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMsg.setSuccess(false);
			jsonMsg.setMsg("删除用户失败!");
			jsonMsg.setObj(e.getMessage());
			return jsonMsg;
		}
		jsonMsg.setSuccess(true);
		jsonMsg.setMsg("删除用户成功!");
		return jsonMsg;
	}
	//返回编辑用户角色页面
	@RequestMapping(value = "/toEditRole")
	public String toEditRole(String userId, Model model) {
		UserDto userModel = userService.getUserByUserId(userId);
		model.addAttribute("userId", userId);
		model.addAttribute("userName", userModel.getUserName());
		return "/User/EditRole";
	}

	// 编辑用户角色
	@RequestMapping(value = "/editRole")
	@ResponseBody
	public JsonMessage editRole(String userId, String roleId) {
		System.out.println("userId: " + userId);
		System.out.println("roleId: " + roleId);
		JsonMessage jsonMsg = new JsonMessage();
		try {
			userService.saveUserRole(userId, roleId);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMsg.setSuccess(false);
			jsonMsg.setMsg("编辑个人角色失败!");
			jsonMsg.setObj(e.getMessage());
			return jsonMsg;
		}
		jsonMsg.setSuccess(true);
		jsonMsg.setMsg("编辑个人角色成功!");
		return jsonMsg;
	}
}
